import { BehaviorSubject } from "rxjs";

class ZxtStorageService {

    // 消息队列
    private dataQueue: { [key: string]: BehaviorSubject<any> }

    constructor() {
        this.dataQueue = {}
    }

    /**
     * 设置全局内存变量，返回当前的 BehaviorSubject
     * @param key 索引
     * @param value 值
     */
    setGlobal<T>(key: string, value: any): BehaviorSubject<T> {
        this.dataQueue[key] = new BehaviorSubject<any>(value)
        return this.dataQueue[key]
    }

    /**
     * 获取指定的全局内存变量 BehaviorSubject
     * @param key 索引
     */
    getGlobal<T>(key: string): BehaviorSubject<T> | null {
        if (!this.dataQueue.hasOwnProperty(key)) return null
        return this.dataQueue[key]
    }

    /**
     * 设置 LocalStorage 变量
     * @param key 索引
     * @param value 值
     */
    setLocalStorage(key: string, value: any): boolean {
        try {
            localStorage[key] = JSON.stringify(value);
            return true
        } catch (error) {
            return false
        }
    }

    /**
    * 获取 LocalStorage 值
    * @param key 索引
    */
    getLocalStorage<T>(key: string): T {
        try {
            return JSON.parse(localStorage[key])
        } catch (error) {
            console.error(error);
            return null
        }
    }

    /**
    * 设置 sessionStorage 变量
    * @param key 索引
    * @param value 值
    */
    setSessionStorage(key: string, value: any): boolean {
        try {
            sessionStorage[key] = JSON.stringify(value);
        } catch (error) {
            console.error(error);
            return false
        }
    }

    /**
    * 获取 sessionStorage 值
    * @param key 索引
    */
    getSessionStorage<T>(key: string): T {
        try {
            return JSON.parse(sessionStorage[key]);
        } catch (error) {
            console.error(error);
            return null
        }
    }

}

let aaa = new ZxtStorageService()


// aaa.setGlobal("asd", { aaa: 111 })

// aaa.getGlobal("asd").subscribe(v => {
//     console.log(v);
// })

// aaa.getGlobal("asd").next("45666")

// aaa.getGlobal("asd").subscribe(v => {
//     console.log(v);
// })


// aaa.setSessionStorage("adafasd", { aaa: 1, bbb: [{ aaaaa: 1 }] })


// console.log(aaa.getSessionStorage("adafasd"));



